const log = require('../util/log'),
  zoroDB = require('../util/zoroDB'),
  urlDao = require('./urlDao'),
  SQL_TABLE = 'word',
  SQL_SELECT = 'select id as wordId, word, p from ' + SQL_TABLE,
  SQL_FIELDS = ['id', 'word', 'p'];

exports.findByWord = (sWord, fn) => {
  global.pool.query(SQL_SELECT + ' where word=? limit 0,1', [sWord], (err, rows, fields) => {
    if (err)
      throw err;
    if (rows.length > 0)
      return fn(rows[0]);
    else
      return fn(null)
  })
}

exports.findByWordId = (wordId, fn) => {
  global.pool.query(SQL_SELECT + ' where id=? limit 0,1', [wordId], (err, rows, fields) => {
    if (err)
      throw err;
    if (rows.length > 0)
      fn(rows[0]);
    else
      fn(null)
  })
}

exports.matchContainWord = (sWord, fn) => {
  fn = fn || (() => {
  });
  global.pool.query(SQL_SELECT + ' where locate(?,word)>0 order by p desc', [sWord], (err, rows, fields) => {
    if (err)
      throw err;
    fn(rows)
  })
}

exports.insert = (word, resolve, reject) => {
  resolve = resolve || (() => {
  });
  reject = reject || (() => {
  });
  global.pool.query('insert into ' + SQL_TABLE + '(word, p) values(?, ?)', [word.word, word.p], (err, result) => {
    if (err) {
      reject(err)
      return
    }
    word.wordId = result.insertId;
    resolve()
  })
}

exports.multiplyPByNotWordId = (lr, wordId, resolve) => {
  resolve = resolve || (() => {
  });
  global.pool.query('update ' + SQL_TABLE + ' set p=p*? where id!=?', [lr, wordId], (err, result) => {
    if (err)
      throw err;
    resolve()
  })
}

exports.update = (word, resolve) => {
  global.pool.query('update ' + SQL_TABLE + ' set word=?, p=? where id=?', [word.word, word.p, word.wordId], (err, result) => {
    if (err)
      throw err;
    resolve()
  })
}

exports.select = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  var sql = 'select * from word where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  zoroDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      log(err)
      resolve([])
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = word => {
  word.getUrls = function (resolve) {
    if (!!this.urls) {
      resolve(this.urls)
      return
    }
    zoroDB.pool.query('select * from url_word where word=?', [word.id], (err, rows, fields) => {
      var promises = [];
      rows.forEach(row => {
        promises.push(new Promise(resolve => {
          urlDao.select({
            id: row.url
          }, urls => {
            urlDao.fillProp(urls[0])
            resolve({
              url: urls[0],
              p: row.p
            })
          })
        }))
      })
      Promise.all(promises).then(urls => {
        this.urls = urls;
        resolve(this.urls)
      })
    })
  }
}
